export default () => {
    type ToastItem = { msg: string, type?: 'warning' | 'danger' | 'success', duration?: number, show: boolean, time: string };

    const toast = useState<ToastItem[]>('toast', () => []);

    const showToast = (item: Omit<ToastItem, 'show' | 'time'>) => {
        // 清除失效toast
        toast.value = toast.value.filter(t => t.show);
        // 生成专属key
        const time = `${+new Date()}`;
        toast.value.push({ ...item, show: true, time });
        setTimeout(() => {
            const t = toast.value.find(t => t.time === time);
            if (t) t.show = false;
        }, item.duration || 2500);
    };

    const topInsetGetter = (item: ToastItem) => {
        if (!item.show) return 0;
        let index = 0;
        const listItem = toast.value.find(i => {
            if (i.show && i.time !== item.time) index++;
            return i.time === item.time;
        });
        if (!listItem) return 0;
        return 42 + index * 74;
    };

    const clearToast = () => {
        toast.value = [];
    };

    return { toast, showToast, topInsetGetter, clearToast };
};